package pe.com.astech.web.dao.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

import pe.com.astech.web.bean.EmpleadoBean;
import pe.com.astech.web.bean.PerfilBean;
import pe.com.astech.web.dao.PerfilDao;
import pe.com.astech.web.exception.DBException;

@Repository
public class PerfilDaoImpl implements PerfilDao{

	
	private JdbcTemplate jdbcTemplate;

	private static final Log log = LogFactory.getLog(PerfilDaoImpl.class);
	
	@Autowired
	public void setDataSource(DataSource dataSource) {
		this.jdbcTemplate = new JdbcTemplate(dataSource);
	}

	
	@Override
	public List<PerfilBean> consultarPerfiles(String cadenaTrazabilidad,
			String nombre) throws DBException {

		String query = "select p.id_perfil,p.nombre from perfil p "
				+ "where p.nombre like :nombre";
		List<PerfilBean> list = new ArrayList<PerfilBean>();
		log.info("query : " + query);
		try {
			MapSqlParameterSource parameters = new MapSqlParameterSource();
		 	parameters.addValue("nombre", "%"+nombre+"%");
		 	
		 	NamedParameterJdbcTemplate namedParameterJdbcTemplate= new NamedParameterJdbcTemplate(jdbcTemplate);
			List<Map<String, Object>> usrRows = namedParameterJdbcTemplate.queryForList(query,parameters);

			for (Map<String, Object> usrRow : usrRows) {

				PerfilBean perfilBean = new PerfilBean();
				perfilBean.setId_perfil(String.valueOf(usrRow.get("id_empleado")));
				perfilBean.setNombre(String.valueOf(usrRow.get("nombre")));

				list.add(perfilBean);
				
			}
		} catch (Exception ex) {
			log.info("Ocurrio un error " + ex.getMessage());
			throw new DBException(ex.getMessage());
		}
		return list;
	}

}
